package cn.stylefeng.guns.modular.household.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * validator校验工具类
 *
 * @author lichenhui
 * @date 2024/03/20
 */
public class ValidatorUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param obj 待校验对象
     * @param groups 带校验组
     */
    public static void validate(Object obj, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new ValidationException(constraint.getMessage());
        }
    }

}
